import { _decorator, Component, Node, Vec3, Quat } from 'cc';
const { ccclass, property, executionOrder } = _decorator;

/**
 * 最终解决方案
 * @date 2025 11/11
 */

@ccclass('BindTransform')
class BindTransform {
    @property
    position: boolean = true;

    @property
    scale: boolean = true;

    @property
    rotation: boolean = true;
}

@ccclass('FollowNode')
@executionOrder(100) //调整脚本执行优先级
export class FollowNode extends Component {
    @property({ type: Node, displayName: '父节点' })
    public borrowParent: Node | null = null;

    @property({ type: Node, displayName: '同步目标' })
    public originalParent: Node | null = null;

    @property({ type: Node, displayName: '被借用的节点' })
    public bindNode: Node | null = null;

    @property
    defaultAttach = false;

    @property(BindTransform)
    transformReq: BindTransform = new BindTransform();

    private _attached: boolean = false;

    protected onLoad(): void {
        if (
            this.defaultAttach &&
            this.borrowParent &&
            this.originalParent &&
            this.bindNode
        ) {
            this.attachTo(
                this.borrowParent,
                this.originalParent,
                this.bindNode,
            );
        }
    }

    /**
     * 将当前节点视觉上附着到目标节点，但保持 transform 不变
     * @param parent 目标节点（模拟挂载的父节点）
     */
    public attachTo(parent: Node, originalParent: Node, current: Node) {
        this.borrowParent = parent;
        this.originalParent = originalParent;
        this.bindNode = current;

        this.bindNode.setParent(this.borrowParent);
        this._attachTarget();

        this.originalParent.on(
            Node.EventType.TRANSFORM_CHANGED,
            this._attachTarget,
            this,
        );

        this._attached = true;
    }

    /**
     * 恢复原始父节点，并保持 transform 不变
     */
    public detach(parent: Node) {
        this.originalParent?.off(
            Node.EventType.TRANSFORM_CHANGED,
            this._attachTarget,
            this,
        );
        if (!this._attached || !parent || !this.bindNode) return;

        const worldPos = this.bindNode.worldPosition.clone();
        const worldRot = this.bindNode.worldRotation.clone();
        const worldScale = this.bindNode.worldScale.clone();

        this.bindNode.setParent(parent);

        this.bindNode.setWorldPosition(worldPos);
        this.bindNode.setWorldRotation(worldRot);
        this.bindNode.setWorldScale(worldScale);

        this._attached = false;
        this.borrowParent = null;
    }

    protected onEnable(): void {
        this._attachTarget();
    }

    /**
     * 每帧同步 transform 到目标节点位置，但保持世界 transform（可视一致）
     */
    update() {
        this._attachTarget();
    }

    private _attachTarget() {
        if (!this._attached || !this.originalParent || !this.bindNode)
            return;

        const subject: Node = this.bindNode;

        const worldPos = this.originalParent.worldPosition.clone();
        const worldRot = this.originalParent.worldRotation.clone();
        const worldScale = this.originalParent.worldScale.clone();

        subject.active =
            this.originalParent.activeInHierarchy &&
            this.originalParent.active;

        // 确保视觉状态稳定
        if (this.transformReq.position) {
            subject.setWorldPosition(worldPos);
        }

        if (this.transformReq.scale) {
            subject.setWorldScale(worldScale);
        }

        if (this.transformReq.rotation) {
            subject.setWorldRotation(worldRot);
        }
    }
}
